package com.wondersgroup.tjfx.common.resultHandler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DecimalFormat;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 单指标专用ResultHandler，处理value，保留2位小数
 * 
 * @author WEI
 * 
 */
@Component("dzbSqlResultHandler")
public class DzbSqlResultHandler implements ResultSetExtractor<JSONArray> {

	@Override
	public JSONArray extractData(ResultSet rs) throws SQLException, DataAccessException {
		JSONArray jsonAry = new JSONArray();
		ResultSetMetaData rm = rs.getMetaData();
		while (rs.next()) {
			JSONObject json = new JSONObject();
			for (int i = 0; i < rm.getColumnCount(); i++) {
				String columnName = rm.getColumnLabel(i + 1).toUpperCase();
				String value = "";
				if ("VALUE".equals(columnName))
					try {
						double v = rs.getDouble(i + 1);
//						value = String.format("%.2f", v);//同样可以四舍五入保留2位小数
						 DecimalFormat df = new DecimalFormat("#.##");
						 value = df.format(v);
						if ("-1".equals(value))
							value = "";
					} catch (Exception e) {
						value = rs.getString(i + 1);
					}
				else
					value = rs.getString(i + 1);
				json.put(columnName, value);
				json.put("type", "dzb");
			}
			jsonAry.add(json);
		}
		return jsonAry;
	}
}
